#!/bin/bash
PROJECT_NAME="k8sdemo"
PROJECT_DIR="/var/jenkins_home/workspace/$PROJECT_NAME"
BUILD_DIR="$PROJECT_DIR/target"
JAR_NAME="HelloKubernetes-0.0.1-SNAPSHOT.jar"
DEPLOY_DIR="/opt/java-app"

# 1. 编译打包
echo "开始构建..."
/opt/maven/bin/mvn clean package -DskipTests || { echo "Maven 构建失败"; exit 1; }

# 2. 部署新版本
echo "部署新应用..."
mkdir -p $DEPLOY_DIR
cp "$BUILD_DIR/$JAR_NAME" $DEPLOY_DIR/
cd $DEPLOY_DIR

# 3. 停止旧进程
echo "停止旧应用..."
pid=$(pgrep -f $JAR_NAME)
if [ -n "$pid" ]; then
  kill -9 $pid
  echo "旧进程已停止"
fi

# 4. 启动新进程
nohup java -jar $JAR_NAME > app.log 2>&1 &

echo "应用部署完成！"